package com.xxgc.helloworld.scheduler;

import com.xxgc.helloworld.job.SendMsgJob;
import lombok.extern.slf4j.Slf4j;
import org.quartz.*;
import org.quartz.impl.StdSchedulerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @program: helloword
 * @description: 任务调度器
 * @author: liutao
 * @create: 2022-03-08 19:08
 **/
@Slf4j
@Component
public class QuartzScheduler {
    //工作名
    private static final String JOB_NAME = "msg_report";
    private static final String JOB_GROUP = "msg_report_group";
    //触发器名
    private static final String TRIGGER_NAME = "msg_report";
    private static final String TRIGGER_GROUP = "msg_report_group";
    //工作任务id
    private static final String JOB_TASK_ID = "msg_task_id";
    private SchedulerFactory schedulerFactory= new StdSchedulerFactory();
    /**
     * quartz 任务调度器
     */
//    @Autowired
    private Scheduler scheduler;
    /**
     * 初始化注入一下调度器
     */
    public QuartzScheduler() throws SchedulerException {
        scheduler = schedulerFactory.getScheduler();
    }

    /**
     * 开始所有任务的方法
     */
    public void startJob() throws SchedulerException {
        scheduler.start();
    }

    public void add(int i,String cron) throws SchedulerException{
        //你想给打工人传的话
        JobDataMap jobDataMap = new JobDataMap();
        jobDataMap.put("msg","好好工作，过年我买大奔");
        // newJob 新建一个工作
        // usingJobData 给工作的打工人传值
        // withIdentity 工作的名称
        JobDetail jobDetail = JobBuilder
                .newJob(SendMsgJob.class)
                .usingJobData(jobDataMap)
                .withIdentity(JOB_NAME + i, JOB_GROUP).build();
        //调度时机  打工时机
        CronScheduleBuilder cronScheduleBuilder = CronScheduleBuilder.cronSchedule(cron);
        // newTrigger 创建一个触发器
        // withIdentity 触发器名
        CronTrigger cronTrigger = TriggerBuilder.newTrigger()
                .withIdentity(TRIGGER_NAME + i, TRIGGER_GROUP)
                .withSchedule(cronScheduleBuilder)
                .build();
        //把打工人和调度器进行绑定
        scheduler.scheduleJob(jobDetail,cronTrigger);
    }

    //移除任务  拯救打工人
    public boolean remove(int i) throws SchedulerException{
        boolean b = scheduler.deleteJob(new JobKey(JOB_NAME + i, JOB_GROUP));
        return b;
    }

}